<?php

namespace app\service\v1;

use think\Exception;
use think\facade\Cache;
use think\facade\Config;

// 管理员token业务类
class ManagerToken extends BaseToken
{
    /**
     * 获取token
     * @param array $managerInfo
     * @return string
     * @throws Exception
     */
    public function getToken(array $managerInfo): string
    {
        $token = self::generateToken();
        $values = [
            'mid'   =>  $managerInfo['id'],
            'role_id'   =>  $managerInfo['role_id'],
            'is_super'  =>  $managerInfo['role']['is_super'] ?? 0,
        ];
        $this->saveToCache($token, $values);
        return $token;
    }

    /**
     * token写入缓存
     * @param string $token
     * @param array $values
     * @return bool
     * @throws Exception
     */
    private function saveToCache(string $token, array $values): bool
    {
        $expire = Config::get('utils.token_expire_in');
        $result = Cache::set($token, json_encode($values), $expire);
        if (!$result) {
            throw new Exception('服务器缓存异常');
        }
        return true;
    }

    /**
     * 缓存获取当前管理员id
     * @return mixed
     * @throws Exception
     */
    public static function getCurrentMID() {
        return self::getInfoByToken('mid');
    }

    /**
     * 缓存获取当前用户角色id
     * @return mixed
     * @throws Exception
     */
    public static function getCurrentRoleId() {
        return self::getInfoByToken('role_id');
    }

    /**
     * 是否是管理员
     * @return bool
     * @throws Exception
     */
    public static function isManager(): bool
    {
        $roleId = self::getCurrentRoleId();
        return $roleId >= 1;
    }

    /**
     * 是否是超管
     * @return bool
     * @throws Exception
     */
    public static function isSuperManager(): bool
    {
        $isAdmin = self::getInfoByToken('is_super');
        return $isAdmin == 1;
    }
}